<template>
  <div id="userLoginView">
    <h2 style="margin-bottom: 16px">用户登录</h2>
    <a-form
      style="max-width: 480px; margin: 0 auto"
      label-align="left"
      auto-label-width
      :model="form"
      @submit="handleSubmit"
    >
      <a-form-item field="userAccount" label="账号">
        <a-input v-model="form.userAccount" placeholder="请输入账号" />
      </a-form-item>
      <a-form-item field="userPassword" tooltip="密码不少于 8 位" label="密码">
        <a-input-password
          v-model="form.userPassword"
          placeholder="请输入密码"
        />
      </a-form-item>
      <a-form-item>
        <!-- 使用 flex 布局将按钮和链接放在同一行 -->
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
          "
        >
          <a-button type="primary" html-type="submit" style="width: 120px">
            登录
          </a-button>
          <a-link href="/user/register" status="success" hoverable>
            没有账号？立即注册
          </a-link>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { UserControllerService, UserLoginRequest } from '../../../generated'
import message from '@arco-design/web-vue/es/message'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

/**
 * 表单信息
 */
const form = reactive({
  userAccount: '',
  userPassword: ''
} as UserLoginRequest)

const router = useRouter()
const store = useStore()

/**
 * 提交表单
 */
const handleSubmit = async () => {
  const res = await UserControllerService.userLoginUsingPost(form)
  // 登录成功，跳转到主页
  if (res.code === 0) {
    //如果登录成功，后台会返回对应用户的身份，并让前端进行更新
    await store.dispatch('user/getLoginUser')
    router.push({
      path: '/',
      replace: true
    })
  } else {
    message.error('登录失败，' + res.message)
  }
}
</script>

<style scoped>
#userLoginView {
  max-width: 480px;
  margin: 0 auto; /* 上下0个像素,左右自适应 */
  padding: 40px 20px; /* 内容上下40个像素,左右20个像素 */
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  background: white;
}
</style>
